<template>
  <div class="result-container">
    <!-- 头部标题 -->
    <div class="header">
      <button class="back-button" @click="navigateBack">返回</button>
      <span class="header-title">查询结果</span>
      <div class="search-keyword">关键词: {{ searchKeyword }}</div>
    </div>
    
    <!-- 加载状态 -->
    <div class="loading-container" v-if="isLoading">
      <div class="spinner"></div>
      <span class="loading-text">查询中...</span>
    </div>

    <!-- 无数据状态 -->
    <div v-else-if="!companyList || companyList.length === 0" class="empty-state">
      <div class="empty-icon">🔍</div>
      <div class="empty-text">未找到相关企业信息</div>
      <button class="empty-button" @click="navigateBack">重新搜索</button>
    </div>

    <!-- 企业信息卡片列表 -->
    <div v-else>
      <!-- 搜索结果统计 -->
      <div class="result-stats">
        共找到 {{ totalRecords }} 条结果
        <span v-if="pagingInfo">（第 {{ pagingInfo.PageIndex }}/{{ totalPages }} 页）</span>
      </div>
      
      <div class="company-card" v-for="(company, index) in companyList" :key="company.KeyNo || index">
        <div class="company-header">
          <span class="company-name">{{ company.Name }}</span>
          <span class="company-status" :class="getStatusClass(company.Status)">{{ company.Status }}</span>
        </div>
        
        <div class="company-info">
          <div class="info-row">
            <span class="info-label">统一信用代码:</span>
            <span class="info-value">{{ company.CreditCode || '暂无' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">法定代表人:</span>
            <span class="info-value">{{ company.LegalPerson || '暂无' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">注册资本:</span>
            <span class="info-value">{{ company.RegisteredCapital || '暂无' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">注册时间:</span>
            <span class="info-value">{{ company.RegisterTime || '暂无' }}</span>
          </div>
          <div class="info-row" v-if="company.Address">
            <span class="info-label">注册地址:</span>
            <span class="info-value address">{{ company.Address }}</span>
          </div>
        </div>
        
        <div class="company-actions">
          <button class="verify-button" @click="verifyCompany(company)">立即认证</button>
        </div>
      </div>

      <!-- 分页控件 -->
      <div v-if="totalPages > 1" class="pagination">
        <button 
          class="page-button" 
          :disabled="currentPage <= 1" 
          @click="changePage(currentPage - 1)"
        >
          上一页
        </button>
        <span class="page-info">第 {{ currentPage }} 页/共 {{ totalPages }} 页</span>
        <button 
          class="page-button" 
          :disabled="currentPage >= totalPages" 
          @click="changePage(currentPage + 1)"
        >
          下一页
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { searchCompanyList } from '@/api'

const router = useRouter()
const route = useRoute()

// 响应式数据
const companyList = ref([])
const isLoading = ref(false)
const searchKeyword = ref('')
const totalRecords = ref(0)
const pagingInfo = ref(null)
const currentPage = ref(1)

// 计算属性
const totalPages = computed(() => {
  if (!pagingInfo.value) return 0
  return Math.ceil(totalRecords.value / pagingInfo.value.PageSize)
})

// 页面加载时获取数据
onMounted(() => {
  loadResultData()
})

// 加载结果数据
const loadResultData = async () => {
  const keyword = route.query.keyword
  const data = route.query.data
  
  searchKeyword.value = keyword || ''
  
  if (data) {
    // 使用传递过来的数据
    try {
      const resultData = JSON.parse(data)
      processApiData(resultData)
    } catch (error) {
      console.error('解析数据失败:', error)
      await searchFromApi(keyword)
    }
  } else {
    // 重新调用API搜索
    await searchFromApi(keyword)
  }
}

// 调用API搜索
const searchFromApi = async (keyword) => {
  if (!keyword) return
  
  isLoading.value = true
  try {
    const res = await searchCompanyList({ keyword: keyword, page: currentPage.value })
    if (res.code === 1) {
      processApiData(res.data)
    } else {
      alert(res.msg || '查询失败')
    }
  } catch (error) {
    console.error('搜索失败:', error)
    alert('网络错误，请重试')
  } finally {
    isLoading.value = false
  }
}

// 处理API返回的数据
const processApiData = (apiData) => {
  if (apiData && apiData.Result) {
    companyList.value = apiData.Result
    totalRecords.value = apiData.Paging?.TotalRecords || apiData.Result.length
    pagingInfo.value = apiData.Paging
    currentPage.value = apiData.Paging?.PageIndex || 1
  } else {
    companyList.value = []
    totalRecords.value = 0
  }
}

// 获取状态样式类
const getStatusClass = (status) => {
  const statusMap = {
    '存续': 'status-active',
    '在业': 'status-active',
    '吊销': 'status-revoked',
    '注销': 'status-cancelled',
    '停业': 'status-closed'
  }
  return statusMap[status] || 'status-unknown'
}

// 返回首页
const navigateBack = () => {
  router.push('/pages/index/index')
}

// 立即认证
const verifyCompany = (company) => {
  const params = new URLSearchParams({
    companyName: company.Name,
    creditCode: company.CreditCode,
    legalPerson: company.LegalPerson,
    orderNumber: company.OrderNumber || ''
  })
  router.push(`/pages/payment/index?${params.toString()}`)
}

// 查看详情
const viewCompanyDetail = (company) => {
  // 这里可以跳转到详情页或显示模态框
  console.log('查看公司详情:', company)
  // 暂时用alert展示详细信息
  const detailInfo = `
公司名称: ${company.Name}
统一信用代码: ${company.CreditCode}
法定代表人: ${company.LegalPerson}
注册资本: ${company.RegisteredCapital}
注册时间: ${company.RegisterTime}
经营状态: ${company.Status}
注册地址: ${company.Address || '暂无'}
  `.trim()
  
  alert(detailInfo)
}

// 分页切换
const changePage = (page) => {
  if (page < 1 || page > totalPages.value) return
  
  currentPage.value = page
  // 这里可以调用API获取指定页面的数据
  searchFromApi(searchKeyword.value)
}
</script>

<style scoped>
.result-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  width: 100%;
  box-sizing: border-box;
  padding-bottom: 20px;
}

/* 头部样式 */
.header {
  background-color: #1890ff;
  color: white;
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  color: white;
  text-align: center;
  flex: 1;
}

.search-keyword {
  font-size: 12px;
  opacity: 0.9;
  text-align: right;
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.back-button {
  background: none;
  border: none;
  color: white;
  font-size: 16px;
  padding: 8px 12px;
  cursor: pointer;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60vh;
  background-color: white;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-text {
  margin-top: 16px;
  font-size: 14px;
  color: #666;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60vh;
  background-color: white;
  padding: 20px;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 16px;
  color: #666;
  margin-bottom: 20px;
  text-align: center;
}

.empty-button {
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 16px;
  font-size: 14px;
  cursor: pointer;
}

/* 搜索结果统计 */
.result-stats {
  background-color: white;
  padding: 12px 16px;
  font-size: 14px;
  color: #666;
  border-bottom: 1px solid #f0f0f0;
}

/* 企业信息卡片 */
.company-card {
  background-color: white;
  margin: 8px 16px 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.company-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 16px 12px;
  border-bottom: 1px solid #f5f5f5;
}

.company-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  flex: 1;
  margin-right: 12px;
}

.company-status {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 12px;
  white-space: nowrap;
}

.status-active {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.status-revoked {
  background-color: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

.status-cancelled {
  background-color: #f5f5f5;
  color: #666;
  border: 1px solid #d9d9d9;
}

.status-closed {
  background-color: #fff7e6;
  color: #fa8c16;
  border: 1px solid #ffd591;
}

.status-unknown {
  background-color: #fafafa;
  color: #999;
  border: 1px solid #e8e8e8;
}

.company-info {
  padding: 12px 16px;
}

.info-row {
  display: flex;
  margin-bottom: 8px;
  align-items: flex-start;
}

.info-label {
  font-size: 13px;
  color: #999;
  min-width: 80px;
  margin-right: 8px;
  flex-shrink: 0;
}

.info-value {
  font-size: 13px;
  color: #333;
  flex: 1;
}

.info-value.address {
  line-height: 1.4;
}

.company-actions {
  display: flex;
  padding: 12px 16px;
  border-top: 1px solid #f5f5f5;
  gap: 8px;
}

.verify-button {
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 16px;
  font-size: 14px;
  flex: 1;
  cursor: pointer;
}

.detail-button {
  background-color: #f5f5f5;
  color: #666;
  border: none;
  border-radius: 4px;
  padding: 8px 16px;
  font-size: 14px;
  flex: 1;
  cursor: pointer;
}

/* 分页控件 */
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background-color: white;
  margin: 0 16px;
  border-radius: 8px;
}

.page-button {
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 12px;
  font-size: 14px;
  cursor: pointer;
}

.page-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.page-info {
  font-size: 14px;
  color: #666;
}

/* 响应式适配 */
@media screen and (max-width: 320px) {
  .company-card {
    margin: 8px 12px 12px;
  }
  
  .company-name {
    font-size: 15px;
  }
  
  .info-label {
    font-size: 12px;
    min-width: 70px;
  }
  
  .info-value {
    font-size: 12px;
  }
}

@media screen and (min-width: 768px) {
  .result-container {
    max-width: 480px;
    margin: 0 auto;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
    min-height: 100vh;
  }
}
</style>